package pers.corvey.studyjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.model.Test;
import pers.corvey.studyjava.model.form.TestForm;
import pers.corvey.studyjava.service.TestService;

@Controller
@RequestMapping("/tests")
public class TestController {

    @Autowired
    private TestService testService;
    
    @GetMapping(headers="Accept=text/html")
    public String showTests() {
        return "forward://html/showTests.html";
    }
    
    @GetMapping(value="/{testId}", headers="Accept=text/html")
    public String showTest() {
        return "forward://html/showTest.html";
    }
    
    @GetMapping
    @ResponseBody
    public Iterable<Test> getTests() {
        return testService.getTests();
    }
    
    @GetMapping("/{testId}")
    @ResponseBody
    public Test getTestById(@PathVariable String testId) {
        return testService.getTestById(testId);
    }
    
    @PostMapping
    @ResponseBody
    public Test createTest(TestForm testForm) {
        testForm.validate();
        Test test = testForm.toTest();
        return testService.createTest(test);
    }
    
    @PutMapping("/{testId}")
    @ResponseBody
    public Test updateTest(@PathVariable String testId, TestForm testForm) {
        testForm.validate();
        Test test = testForm.toTest();
        test.setId(testId);
        return testService.updateTest(test);
    }
    
    @DeleteMapping("/{testId}")
    @ResponseBody
    public void deleteTestById(@PathVariable String testId) {
        testService.deleteTestById(testId);
    }
}
